package com.test.proxy.java;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-06-17 下午12:35
 */
public class JdkProxy implements InvocationHandler {

    private final Object subject;

    public JdkProxy(Object subject) {
        this.subject = subject;
    }

    /**
     * 获取动态代理对象
     *
     * @param target
     * @return
     */
    public static Object getProxy(Object target) {
        InvocationHandler handler = new JdkProxy(target);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("this method is using jdk proxy");
        if (Objects.nonNull(subject)) {
            return method.invoke(subject, args);
        }
        return null;
    }
}
